package com.tbl.modules.wms2.service.impl.ordermanage.asn;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.wms.dao.baseinfo.WarehouseDAO;
import com.tbl.modules.wms.entity.baseinfo.Warehouse;
import com.tbl.modules.wms2.dao.ordermanage.asn.AsnLineDAO;
import com.tbl.modules.wms2.dao.purchasein.PurchaseOrderDAO;
import com.tbl.modules.wms2.entity.operation.YclInOutFlowEntity;
import com.tbl.modules.wms2.entity.ordermanage.asn.AsnCorrectDTO;
import com.tbl.modules.wms2.entity.ordermanage.asn.AsnLineEntity;
import com.tbl.modules.wms2.entity.ordermanage.asn.AsnLineUpdateDTO;
import com.tbl.modules.wms2.entity.ordermanage.delivery.DeliveryEntity;
import com.tbl.modules.wms2.entity.purchasein.PurchaseOrderSaveEntity;
import com.tbl.modules.wms2.entity.report.YclInventoryEntity;
import com.tbl.modules.wms2.service.operation.YclInOutFlowService;
import com.tbl.modules.wms2.service.ordermanage.asn.AsnLineService;
import com.tbl.modules.wms2.service.ordermanage.delivery.DeliveryService;
import com.tbl.modules.wms2.service.report.InventoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;

@Service("yclAsnLineService")
public class AsnLineServiceImpl extends ServiceImpl<AsnLineDAO, AsnLineEntity> implements AsnLineService {

    @Resource
    private AsnLineDAO asnLineDAO;

    @Resource
    DeliveryService deliveryService;

    @Resource
    YclInOutFlowService yclInOutFlowService;

    @Resource
    WarehouseDAO warehouseDAO;

    @Resource
    PurchaseOrderDAO purchaseOrderDAO;

    @Resource(name = "yclInventoryService")
    InventoryService inventoryService;


    public PageUtils getPageList(PageTbl pageTbl, Map<String, Object> map) {
        String sortName = pageTbl.getSortname();
        String sortOrder = pageTbl.getSortorder();
        if (StringUtils.isEmptyString(sortName)) {
            sortName = "";
        }
        if (StringUtils.isEmptyString(sortOrder)) {
            sortOrder = "desc";
        }
        Page page = new Page(pageTbl.getPageno(), pageTbl.getPagesize(), sortName, "asc".equalsIgnoreCase(sortOrder));
        return new PageUtils(page.setRecords(asnLineDAO.getPageList(page, map)));
    }

    @Override
    public void insertAsnLine(AsnLineEntity asnLineEntity) {
        asnLineDAO.insert(asnLineEntity);
    }

    @Override
    public Boolean editAsnLine(AsnLineEntity asnLineEntity) {
        return this.insertOrUpdate(asnLineEntity);
    }

    @Override
    public Boolean editAsnLineBatch(List<AsnLineUpdateDTO> asnLineUpdateDTOS) {

        AsnLineEntity asnLineEntity = new AsnLineEntity();
        DeliveryEntity deliveryEntity = new DeliveryEntity();

        List<YclInOutFlowEntity> yclInOutFlowEntities = new ArrayList<>();

        for (AsnLineUpdateDTO item : asnLineUpdateDTOS) {

            if ("SHD".equals(item.getBusinessCode().substring(0, 3))) {

                // 回改送货单详情
                if (StrUtil.isNotEmpty(item.getAsnLineId())) {
                    asnLineEntity.setAsnLineId(item.getAsnLineId());
                    asnLineEntity.setCancelQuantity(item.getUpdownQuantity());
//                asnLineEntity.setLocatorCode(item.getLocatorCode());
                    asnLineEntity.setStatus("1");
                    this.editAsnLine(asnLineEntity);
                }

                YclInOutFlowEntity yclInOutFlowEntity = new YclInOutFlowEntity();
                BeanUtils.copyProperties(item, yclInOutFlowEntity);
                yclInOutFlowEntity.setInoutType("1");

                // 判断是否质检通过
                deliveryEntity.setAsnNumber(item.getAsnNumber());
                deliveryEntity.setPoCode(item.getPoCode());
                deliveryEntity.setPoLineNum(item.getPoLineNum());
                DeliveryEntity deliveryServiceOne = deliveryService.getOne(deliveryEntity);

                if ("1".equals(deliveryServiceOne.getIsPass())) {
                    yclInOutFlowEntity.setIsIn("1");

                    // TODO 更新EBS库存
                    Map map = new HashMap(1);
                    map.put("code", item.getStoreCode());
                    map.put("entityId", item.getAreaCode());
                    Warehouse warehouseByCode = warehouseDAO.getWarehouseByCode(map);
                    PurchaseOrderSaveEntity purchaseOrderSaveEntity = new PurchaseOrderSaveEntity();
                    purchaseOrderSaveEntity.setPoLineId(Long.valueOf(item.getPoLineId()));
                    purchaseOrderSaveEntity.setLoctorId(warehouseByCode.getLocatorId());
                    purchaseOrderSaveEntity.setSubCode(item.getStoreCode());
                    purchaseOrderSaveEntity.setTransDate(new Timestamp(System.currentTimeMillis()));
                    purchaseOrderSaveEntity.setVendorLot(item.getLotsNum());
                    purchaseOrderSaveEntity.setSourceId(deliveryServiceOne.getID());
                    purchaseOrderSaveEntity.setQuantity(Double.valueOf(String.valueOf(item.getUpdownQuantity())));
                    purchaseOrderDAO.savePurchaseOrder(purchaseOrderSaveEntity);

                    // TODO
                    if ("S".equals(purchaseOrderSaveEntity.getRetCode())) {
                        Long rcvLineId = purchaseOrderSaveEntity.getRcvLineId();

                        deliveryServiceOne.setEbsLineId(String.valueOf(rcvLineId));
                        deliveryEntity.setDeliverQuantity(item.getUpdownQuantity());
                        deliveryService.edit(deliveryServiceOne);

                    } else if ("E".equals(purchaseOrderSaveEntity.getRetCode())) {
                        String retMess = purchaseOrderSaveEntity.getRetMess();
                        return false;
                    }

                } else {
                    yclInOutFlowEntity.setIsIn("0");
                }
                yclInOutFlowEntities.add(yclInOutFlowEntity);

            } else { // 退货

                // 无库位
                if (StrUtil.isBlank(item.getLocatorCode())) {
                    YclInOutFlowEntity yclInOutFlowEntity = new YclInOutFlowEntity();
                    BeanUtils.copyProperties(item, yclInOutFlowEntity);
                    yclInOutFlowEntities.add(yclInOutFlowEntity);
                } else {
                    YclInventoryEntity yclInventoryEntity = inventoryService.find(item.getAreaCode(), item.getStoreCode(), item.getLocatorCode(), item.getMaterialCode(), item.getLotsNum());
                    // 无库存
                    if (yclInventoryEntity == null) {
                        return false;
                    } else {
                        // 下架大于库存
                        if (item.getUpdownQuantity().compareTo(yclInventoryEntity.getQuality()) == 1) {
                            return false;
                        }
                        YclInOutFlowEntity yclInOutFlowEntity = new YclInOutFlowEntity();
                        BeanUtils.copyProperties(item, yclInOutFlowEntity);
                        yclInOutFlowEntity.setInoutType("0");
                        yclInOutFlowEntities.add(yclInOutFlowEntity);


                        deliveryEntity.setMaterialCode(item.getMaterialCode());
                        deliveryEntity.setLotsNum(item.getLotsNum());
                        deliveryEntity.setEntityId(item.getAreaCode());
                        DeliveryEntity deliveryServiceOne = deliveryService.getOne(deliveryEntity);

                        Map map = new HashMap(2);
                        map.put("rcvLineId", Long.parseLong(deliveryServiceOne.getEbsLineId()));
                        map.put("quantity", Double.parseDouble(String.valueOf(item.getUpdownQuantity())));
                        purchaseOrderDAO.returnPurchaseOrder(map);

                        // TODO
                        if ("S".equals((String) map.get("retCode"))) {

                        } else if ("E".equals((String) map.get("retCode"))) {

                            return false;
                        } else {
                            return false;
                        }

                    }

                }

            }

        }

        return yclInOutFlowService.saveBatch(yclInOutFlowEntities);
    }

    @Override
    public Boolean updateAsnLine(AsnLineEntity asnLineEntity) {
        Wrapper ew = new EntityWrapper<AsnLineEntity>();
        ew.eq("PO_CODE", asnLineEntity.getPoCode());
        return this.update(asnLineEntity, ew);
    }

    @Override
    public List<AsnLineEntity> listViewLine(String asnHeaderIds) {
        List<AsnLineEntity> list = asnLineDAO.listViewLine(asnHeaderIds);
        return list;
    }

    @Override
    public List<AsnLineEntity> listViewLineListMap(List<Map> list) {
        List<AsnLineEntity> lineEntityList = new ArrayList<>();
        Wrapper ew = new EntityWrapper<AsnLineEntity>();
        for (int i = 0; i < list.size(); i++) {
            String poCode = (String) list.get(i).get("poCode");
            String poLineNum = (String) list.get(i).get("poLineNum");
            ew.eq("PO_CODE", poCode).eq("PO_LINE_NUM", poLineNum);
            List<AsnLineEntity> list1 = this.selectList(ew);
            lineEntityList.addAll(list1);
        }
        return lineEntityList;
    }

    @Override
    public List<AsnCorrectDTO> listViewAsnByPoCode(String poCodes) {

        return asnLineDAO.listViewAsnByPoCode(poCodes);
    }


}